//
//  PressHouseResouceViewController.m
//  Fangmm
//
//  Created by ChaoZhou on 16/3/12.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "PressHouseResouceViewController.h"
#import "PressNormalTableViewCell.h"
#import "PressHousePhotoTableViewCell.h"
#import "HttpServer.h"
#import "Utility.h"
#import "Constants.h"
#import "PressHouseStyleViewController.h"
#import "BasicViewController.h"
#import <MLSelectPhotoPickerViewController.h>
#import <MLSelectPhotoAssets.h>
#import <TSMessages/TSMessageView.h>
#import <MobClick.h>
@interface PressHouseResouceViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PressHousePhotoTableViewCellDelegate,PressHouseStyleViewControllerDelegate,BasicViewControllerDelegate,UITextViewDelegate,UIActionSheetDelegate>
{
    NSMutableArray      *photoArray;
    NSMutableArray      *photoDataArray;
    UIAlertController   *alert;
    House               *pressHouse;
    UIImagePickerController *cameraPicker;
    NSString            *fileString;
    UITableViewCell     *descCell;
    UITextView          *textView;
    PressNormalTableViewCell *communityCell;
    PressNormalTableViewCell *houseStyleCell;
    PressNormalTableViewCell *rentCell;
    PressNormalTableViewCell *timeCell;


}
@end

@implementation PressHouseResouceViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"发布房源页"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"发布房源页"];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    photoArray = [NSMutableArray array];
    photoDataArray = [NSMutableArray array];
    fileString = @"";
    pressHouse  = [House new];
    [_mainTabelView registerNib:[UINib nibWithNibName:@"PressNormalTableViewCell" bundle:nil]forCellReuseIdentifier:@"PressNormalTableViewCell"];
    [_mainTabelView registerNib:[UINib nibWithNibName:@"PressHousePhotoTableViewCell" bundle:nil] forCellReuseIdentifier:@"PressHousePhotoTableViewCell"];
    self.title = @"发布房源";
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(clickToBack)];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"发布房源" style:UIBarButtonItemStyleDone target:self action:@selector(clickToPress)];
    [rightBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1],NSFontAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = leftBar;
    self.navigationItem.rightBarButtonItem = rightBar;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section)
    {
        case 0:
            return 50;
            break;
        default:
        {
            switch (indexPath.row)
            {
                case 0:
                    return 50;
                    break;
                case 1:
                    return 80;
                    break;
                case 2:
                    return 50;
                    break;
                default:
                {
                    return 150;
                }
                    break;
            }
        }
            break;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                communityCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                communityCell.titleLabel.text  = @"小区";
                communityCell.contentTextField.placeholder = @"请输入小区名称";
                communityCell.rowImage.hidden = YES;
                return communityCell;
            }
                break;
            case 1:
            {
                houseStyleCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                houseStyleCell.titleLabel.text = @"户型";
                houseStyleCell.contentTextField.placeholder = @"请选择户型";
                houseStyleCell.contentTextField.userInteractionEnabled = NO;
                return houseStyleCell;
            }
                break;
            case 2:
            {
                rentCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                rentCell.titleLabel.text = @"租金";
                rentCell.contentTextField.placeholder = @"请输入租金";
                rentCell.contentTextField.keyboardType = UIKeyboardTypeNumberPad;
                rentCell.rowImage.hidden = YES;
                return rentCell;
            }
                break;
            default:
            {
                timeCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                timeCell.titleLabel.text = @"入住时间";
                timeCell.contentTextField.userInteractionEnabled = NO;
                timeCell.contentTextField.placeholder = @"请设置入住时间";
                timeCell.contentTextField.text = pressHouse.rentTime;
                return timeCell;
            }
                break;
        }
    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
            {
                PressNormalTableViewCell *photoTitleCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                photoTitleCell.titleLabel.text = @"房源照片";
                photoTitleCell.contentTextField.hidden = YES;
                photoTitleCell.rowImage.hidden = YES;
                return photoTitleCell;
            }
                break;
            case 1:
            {
                PressHousePhotoTableViewCell *photoCell = [tableView dequeueReusableCellWithIdentifier:@"PressHousePhotoTableViewCell"];
                photoCell.delegate = self;
                [self rectPhotoCell:photoCell];
                return photoCell;
            }
                break;
            case 2:
            {
                PressNormalTableViewCell *descTitleCell = [tableView dequeueReusableCellWithIdentifier:@"PressNormalTableViewCell"];
                descTitleCell.titleLabel.text = @"房源描述(必填)";
                descTitleCell.contentTextField.hidden = YES;
                descTitleCell.rowImage.hidden = YES;
                return descTitleCell;
            }
                break;
            default:
            {
                if (!descCell)
                {
                    descCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
                    descCell.selectionStyle = UITableViewCellSelectionStyleNone;
                    textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 5, self.view.bounds.size.width - 20, 140)];
                    textView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1];
                    textView.delegate = self;
                    [descCell addSubview:textView];
                }
                if ([textView.text isEqualToString:@""])
                {
                }
                else
                {
                    pressHouse.comment = textView.text;
                }
                NSLog(@"&&&&&%@",pressHouse.comment);
                return descCell;
            }
                break;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [_mainTabelView setContentOffset:CGPointMake(0, 0)];
    if (indexPath.section == 0 &&  indexPath.row == 1)
    {
        NSLog(@"选择了户型cell");
        PressHouseStyleViewController *houseStyleVC = [[PressHouseStyleViewController alloc]init];
        houseStyleVC.delegate = self;
        [self presentViewController:houseStyleVC animated:YES completion:nil];
    }
    if (indexPath.section == 0 && indexPath.row == 3)
    {
        NSLog(@"选择了入住时间cell");
        BasicViewController *calenderVC = [[BasicViewController alloc]init];
        calenderVC.delegate = self;
        [self presentViewController:calenderVC animated:YES completion:nil];
    }
}
#pragma mark - BasicViewControllerDelegate
-(void)setMoveTimeWithDate:(NSString *)date
{
    pressHouse.rentTime = date;
    [_mainTabelView reloadData];
}

#pragma navigationmethod
-(void)clickToBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)clickToPress
{
    pressHouse.community = communityCell.contentTextField.text;
    pressHouse.rent = [rentCell.contentTextField.text intValue];
    pressHouse.comment = textView.text;
    pressHouse.cityCode  = [[Utility getObjectForKey:kCityCode] intValue];
    pressHouse.userId    = [Utility getObjectForKey:kUserId];
    pressHouse.fileIds   = fileString;
    if ([pressHouse.community isEqualToString:@""] || (pressHouse.roomNum + pressHouse.hallNum + pressHouse.toiletNum) == 0 || pressHouse.rent == 0 || [pressHouse.rentTime isEqualToString:@""] || [pressHouse.comment isEqualToString:@""] || [pressHouse.fileIds isEqualToString:@""])
    {
        [TSMessage showNotificationInViewController:self title:@"发布失败!" subtitle:@"请完善房源信息" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
    }
    else
    {
        [HttpServer PostHouseWithHouse:pressHouse WithSuccessBlock:^(NSDictionary *responseData)
         {
             NSLog(@"发布返回数据%@",responseData);
             if ([responseData[@"code"] integerValue] == 0)
             {
                 [TSMessage showNotificationInViewController:self title:@"发布房源成功!" subtitle:@"" type:TSMessageNotificationTypeSuccess duration:2.0 canBeDismissedByUser:true];
             }
             else
             {
                 [TSMessage showNotificationInViewController:self title:@"发布房源失败!" subtitle:@"" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
             }
         } withFailedBlock:^(id errorMsg)
         {
             NSLog(@"发布错误数据%@",errorMsg);
         }];
    }
    
}
#pragma mark - 绘制photocell
-(void)rectPhotoCell:(PressHousePhotoTableViewCell*)photoCell
{
    switch (photoArray.count)
    {
        case 0:
        {
            [photoCell.buttonView0 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.userInteractionEnabled = YES;
            photoCell.buttonView1.userInteractionEnabled = NO;
            photoCell.buttonView2.userInteractionEnabled = NO;
            photoCell.buttonView3.userInteractionEnabled = NO;
            photoCell.buttonView4.userInteractionEnabled = NO;
            photoCell.buttonView5.userInteractionEnabled = NO;
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = YES;
            photoCell.buttonView2.hidden = YES;
            photoCell.buttonView3.hidden = YES;
            photoCell.buttonView4.hidden = YES;
            photoCell.buttonView5.hidden = YES;
            
        }
            break;
        case 1:
        {
            [photoCell.buttonView0 setBackgroundImage:photoArray[0] forState:UIControlStateNormal];
            [photoCell.buttonView1 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = NO;
            photoCell.buttonView2.hidden = YES;
            photoCell.buttonView3.hidden = YES;
            photoCell.buttonView4.hidden = YES;
            photoCell.buttonView5.hidden = YES;
            photoCell.buttonView0.userInteractionEnabled = NO;
            photoCell.buttonView1.userInteractionEnabled = YES;
            photoCell.buttonView2.userInteractionEnabled = NO;
            photoCell.buttonView3.userInteractionEnabled = NO;
            photoCell.buttonView4.userInteractionEnabled = NO;
            photoCell.buttonView5.userInteractionEnabled = NO;
        }
            break;
        case 2:
        {
            [photoCell.buttonView0 setBackgroundImage:photoArray[0] forState:UIControlStateNormal];
            [photoCell.buttonView1 setBackgroundImage:photoArray[1] forState:UIControlStateNormal];
            [photoCell.buttonView2 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = NO;
            photoCell.buttonView2.hidden = NO;
            photoCell.buttonView3.hidden = YES;
            photoCell.buttonView4.hidden = YES;
            photoCell.buttonView5.hidden = YES;
            photoCell.buttonView0.userInteractionEnabled = NO;
            photoCell.buttonView1.userInteractionEnabled = NO;
            photoCell.buttonView2.userInteractionEnabled = YES;
            photoCell.buttonView3.userInteractionEnabled = NO;
            photoCell.buttonView4.userInteractionEnabled = NO;
            photoCell.buttonView5.userInteractionEnabled = NO;
        }
            break;
        case 3:
        {
            [photoCell.buttonView0 setBackgroundImage:photoArray[0] forState:UIControlStateNormal];
            [photoCell.buttonView1 setBackgroundImage:photoArray[1] forState:UIControlStateNormal];
            [photoCell.buttonView2 setBackgroundImage:photoArray[2] forState:UIControlStateNormal];
            [photoCell.buttonView3 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = NO;
            photoCell.buttonView2.hidden = NO;
            photoCell.buttonView3.hidden = NO;
            photoCell.buttonView4.hidden = YES;
            photoCell.buttonView5.hidden = YES;
            photoCell.buttonView0.userInteractionEnabled = NO;
            photoCell.buttonView1.userInteractionEnabled = NO;
            photoCell.buttonView2.userInteractionEnabled = NO;
            photoCell.buttonView3.userInteractionEnabled = YES;
            photoCell.buttonView4.userInteractionEnabled = NO;
            photoCell.buttonView5.userInteractionEnabled = NO;
        }
            break;
        case 4:
        {
            [photoCell.buttonView0 setBackgroundImage:photoArray[0] forState:UIControlStateNormal];
            [photoCell.buttonView1 setBackgroundImage:photoArray[1] forState:UIControlStateNormal];
            [photoCell.buttonView2 setBackgroundImage:photoArray[2] forState:UIControlStateNormal];
            [photoCell.buttonView2 setBackgroundImage:photoArray[3] forState:UIControlStateNormal];
            [photoCell.buttonView4 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = NO;
            photoCell.buttonView2.hidden = NO;
            photoCell.buttonView3.hidden = NO;
            photoCell.buttonView4.hidden = NO;
            photoCell.buttonView5.hidden = YES;
            photoCell.buttonView0.userInteractionEnabled = NO;
            photoCell.buttonView1.userInteractionEnabled = NO;
            photoCell.buttonView2.userInteractionEnabled = NO;
            photoCell.buttonView3.userInteractionEnabled = NO;
            photoCell.buttonView4.userInteractionEnabled = YES;
            photoCell.buttonView5.userInteractionEnabled = NO;
        }
            break;
        default:
        {
            [photoCell.buttonView0 setBackgroundImage:photoArray[0] forState:UIControlStateNormal];
            [photoCell.buttonView1 setBackgroundImage:photoArray[1] forState:UIControlStateNormal];
            [photoCell.buttonView2 setBackgroundImage:photoArray[2] forState:UIControlStateNormal];
            [photoCell.buttonView3 setBackgroundImage:photoArray[3] forState:UIControlStateNormal];
            [photoCell.buttonView4 setBackgroundImage:photoArray[4] forState:UIControlStateNormal];
            [photoCell.buttonView4 setBackgroundImage:[UIImage imageNamed:@"photo_add"] forState:UIControlStateNormal];
            photoCell.buttonView0.hidden = NO;
            photoCell.buttonView1.hidden = NO;
            photoCell.buttonView2.hidden = NO;
            photoCell.buttonView3.hidden = NO;
            photoCell.buttonView4.hidden = NO;
            photoCell.buttonView5.hidden = NO;
            photoCell.buttonView0.userInteractionEnabled = NO;
            photoCell.buttonView1.userInteractionEnabled = NO;
            photoCell.buttonView2.userInteractionEnabled = NO;
            photoCell.buttonView3.userInteractionEnabled = NO;
            photoCell.buttonView4.userInteractionEnabled = NO;
            photoCell.buttonView5.userInteractionEnabled = NO;
        }
            break;
    }
}

#pragma mark -addphotoDelegate
-(void)addPhotoClickButton:(UIButton *)sender
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        if (sender.tag < photoArray.count)
        {
            NSLog(@"查看照片");
        }
        else if(sender.tag == photoArray.count)
        {
            NSLog(@"添加照片");
            alert = [UIAlertController alertControllerWithTitle:@"图片上传方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                              {
                                                  cameraPicker = [[UIImagePickerController alloc]init];
                                                  cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                  cameraPicker.delegate = self;
                                                  [self presentViewController:cameraPicker animated:YES completion:nil];
                                              }];
            UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                          {
                                              // alloc
                                              MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
                                              // Default Push CameraRoll
                                              pickerVc.status = PickerViewShowStatusCameraRoll;
                                              // Limit Count.
                                              pickerVc.maxCount = 9;
                                              // Push
                                              [self presentViewController:pickerVc animated:YES completion:nil];
                                              pickerVc.callBack = ^(NSArray *assets)
                                              {
                                                  photoDataArray = [NSMutableArray array];
                                                  for (MLSelectPhotoAssets *image in assets)
                                                  {
                                                      NSLog(@"++++%@",image);
                                                      
                                                      [photoArray addObject:[image originImage]];
//                                                      NSData *data = UIImagePNGRepresentation([image originImage]);
                                                      NSData *data =
                                                      UIImageJPEGRepresentation([image originImage], 0.6);
                                                      [photoDataArray addObject:data];
                                                      [_mainTabelView reloadData];
                                                  }
                                                  NSLog(@"图片＝＝ %@",assets);
#warning 调用上传图片方法；
                                                  [self uploadPhoto];
                                                  
                                              };
                                          }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancelAction];
            [alert addAction:takePhotoAction];
            [alert addAction:albumAction];
        }
        [self presentViewController:alert animated:YES completion:nil];
    }
    else
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"图片上传方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"相册", nil];
        [actionSheet showInView:self.view];
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"点击了%ld",(long)buttonIndex);
    if (buttonIndex == 0)
    {
        //相机
        cameraPicker = [[UIImagePickerController alloc]init];
        cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        cameraPicker.delegate = self;
        [self presentViewController:cameraPicker animated:YES completion:nil];
    }
    else
    {
        // alloc
        MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
        // Default Push CameraRoll
        pickerVc.status = PickerViewShowStatusCameraRoll;
        // Limit Count.
        pickerVc.maxCount = 9;
        // Push
        [self presentViewController:pickerVc animated:YES completion:nil];
        pickerVc.callBack = ^(NSArray *assets)
        {
            photoDataArray = [NSMutableArray array];
            for (MLSelectPhotoAssets *image in assets)
            {
                NSLog(@"++++%@",image);
                
                [photoArray addObject:[image originImage]];
                NSData *data = UIImagePNGRepresentation([image originImage]);
                [photoDataArray addObject:data];
                [_mainTabelView reloadData];
            }
            NSLog(@"图片＝＝ %@",assets);
            [self uploadPhoto];
        };
    }
}
#pragma mark - 上传图片
#warning  上传图片
#pragma mark - presshouseStyleDelegate
-(void)ConfigTheHouseStyleWith:(House *)house
{
    pressHouse.roomNum = house.roomNum;
    pressHouse.hallNum = house.hallNum;
    pressHouse.toiletNum = house.toiletNum;
     NSString *houseStyleStr = [NSString stringWithFormat:@"%d室%d厅%d卫",pressHouse.roomNum,pressHouse.hallNum,pressHouse.toiletNum];
                houseStyleCell.contentTextField.text = houseStyleStr;
    [_mainTabelView reloadData];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
#warning 调用上传图片方法
    if (picker == cameraPicker)
    {
        NSLog(@"相机输出%@",info);
        UIImage *pickerImage = info[@"UIImagePickerControllerOriginalImage"];
        [photoArray addObject:pickerImage];
        [_mainTabelView reloadData];
        [self dismissViewControllerAnimated:true completion:nil];
        photoDataArray = [NSMutableArray array] ;
        [photoDataArray addObject:UIImagePNGRepresentation(pickerImage)];
        [self uploadPhoto];
    }
}
#pragma mark - 上传图片
-(void)uploadPhoto
{
    [TSMessage showNotificationWithTitle:@"上传房源照片中..." type:TSMessageNotificationTypeWarning];
    [HttpServer upLoadHousePhotoWithDataArray:photoDataArray withSuccessBlock:^(NSDictionary *responseData)
     {
         NSLog(@"上传图片返回数据%@",responseData);
         NSArray *resourceArray = responseData[@"resources"];
         for (NSDictionary *resourceDic in resourceArray)
         {
             fileString = [NSString stringWithFormat:@"%@,%@",fileString,resourceDic[@"uuid"]];
             [TSMessage dismissActiveNotification];
         }
     }
     withFailedBlock:^(id errorMsg)
     {
         NSLog(@"上传图片返回错误%@",errorMsg);
     }];
}
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    self.mainTabelView.contentOffset = CGPointMake(0, 240);
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    self.mainTabelView.contentOffset = CGPointMake(0, -240);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
